print('Wait link to wifi')
wifi.setmode(wifi.STATION)
wifi.sta.sethostname("Node-RGB")
station_cfg={}
station_cfg.ssid="xxxxx" --设置WiFi SSID
station_cfg.pwd="xxxxxx" --设置WiFi密码
wifi.sta.config(station_cfg)
ws2812.init()
local color,speed,brightness,mode = "255,63,0",200,100,"static"
strip_buffer = ws2812.newBuffer(215, 3)
strip_buffer:fill(255,165,0)
ws2812.write(strip_buffer)
ws2812_effects.init(strip_buffer)
mytimer = tmr.create()
mytimer:alarm(1000, 1, function()
  if wifi.sta.getip() == nil then
    print('Waiting for IP ...')
  else
    print('IP is ' .. wifi.sta.getip())
    print('WIFI LINK OK')
    effectsInit()
    mqttInit()
    mytimer:stop()
  end 
end)

--效果切换
function effectsInit()
  local aa = lua_string_split(color,",")
  r = aa[1]
  g = aa[2]
  b = aa[3]
  ws2812_effects.set_speed(speed)
  ws2812_effects.set_brightness(brightness)
  if mode == "static" or mode == "blink" or mode == "color_wipe" or mode == "larson_scanner" or mode == "color_wipe" or mode == "random_dot" then
    ws2812_effects.set_color(g,r,b)
    ws2812_effects.set_mode(mode)
  elseif mode == "flicker" then
    ws2812_effects.set_color(g,r,b)
    ws2812_effects.set_mode(mode,50)
  elseif mode == "gradient" then
    ws2812_effects.set_mode(mode, string.char(0,200,0,200,200,0,0,200,0))
  else
    ws2812_effects.set_mode(mode)
  end
  ws2812_effects.start()
end

--连接mqtt服务，监听消息
function mqttInit()
  m = mqtt.Client("NodeRGB", 60, "mqtt", "mqtt")  
  m:lwt("/lwt", "offline", 0, 0)
  m:on("connect", function(client) print ("connected") end)
  m:on("offline", function(client) print ("offline") end)
  m:on("message", function(client, topic, data)
    print(topic .. ":" )
    if data ~= nil then
      print(data)
      --在不支持调色模式时丢弃收到的调色数据
      if topic == "ws2812/setcolor" then
        if mode == "static" or mode == "blink" or mode == "color_wipe" or mode == "flicker" or mode == "larson_scanner" or mode == "color_wipe" or mode == "random_dot" then
          color = data
        end
        m:publish("ws2812/setcolorpub", color, 0, 0, function(client) print("sent_color:" .. color) end)
      --设置模式
      elseif topic == "ws2812/seteffect" then
        mode = data
        m:publish("ws2812/seteffectpub", mode, 0, 0, function(client) print("sent_seteffect:" .. mode) end)
      --设置动画速度
      elseif topic == "ws2812/setspeed" then
        speed = data
        effectsInit()
        m:publish("ws2812/switchpub", "ON", 0, 0)
        m:publish("ws2812/setspeedpub", speed, 0, 0, function(client) print("sent_setspeed:" .. speed) end)
      --设置亮度
      elseif topic == "ws2812/setbrightness" then
        brightness = data
        m:publish("ws2812/setbrightnesspub", brightness, 0, 0, function(client) print("sent_brightness:" .. brightness) end)
      --设置开关（非断电，仅将颜色设置为0,0,0）
      elseif topic == "ws2812/switch" then
        if data == "OFF" then
          ws2812_effects.stop()
          strip_buffer:fill(0,0,0)
          ws2812.write(strip_buffer)
        elseif data == "ON" then 
          effectsInit()
        end
        m:publish("ws2812/switchpub", data, 0, 0, function(client) print("sent_switch:ON") end)
      end
    end
  end)
  --这里设置mqtt服务器信息
  m:connect("192.168.1.10", 1883, 0, function(client)
    print("connected")
    m:subscribe({["ws2812/switch"]=0,["ws2812/setcolor"]=0,["ws2812/setbrightness"]=0,["ws2812/setspeed"]=0,["ws2812/seteffect"]=0}, function(conn) print("subscribe success") end)
    --多次调用publish时，所有发布命令只会调用最后定义的回调函数
    m:publish("ws2812/switchpub", "ON", 0, 0)
    m:publish("ws2812/setcolorpub", color, 0, 0)
    m:publish("ws2812/setbrightnesspub", brightness, 0, 0)
    m:publish("ws2812/seteffectpub", mode, 0, 0)
    m:publish("ws2812/setspeedpub", speed, 0, 0, function(client) print("Synchronous state completion") end)
  end,
  function(client, reason)
    print("failed reason: " .. reason)
  end)
  --m:close();
end

--字符串分割函数
function lua_string_split(str, split_char)
  local sub_str_tab = {};
  while (true) do
          local pos = string.find(str, split_char);
          if (not pos) then
                  sub_str_tab[#sub_str_tab + 1] = str;
                  break;
          end
          local sub_str = string.sub(str, 1, pos - 1);
          sub_str_tab[#sub_str_tab + 1] = sub_str;
          str = string.sub(str, pos + 1, #str);
  end
  return sub_str_tab;
end
